<?php
import("@.Service.BaseService");
import("@.DAO.UserDAO");
import("@.DAO.OrgDAO");

class UserService extends BaseService
{
    //错误代码
    const CREATE_USER_FAILED = -1;//创建用户失败
    const CREATE_ORG_FAILED = -2;//创建组织失败
    const SQL_ERROR = -3;//数据库错误
    const ACCT_NOT_EXISTS_OR_PSD_NOT_RIGHT = -4;//账户不存在或密码错误

    const LOG_PREFIX = 'UserService->';

    protected static $instance = null;

    protected function __construct()
    {
        $this->userDAO = UserDAO::getInstance();
        $this->orgDAO = OrgDAO::getInstance();
    }

    private function __clone()
    {
    }

    private $userDAO;
    private $orgDAO;

    //注册新用户,如果错误返回错误码,如果正确返回接口定义的data参数
    public function createUser($params)
    {
        $User = $params['User'];
        $Org = $params['Org'];

        $User->startTrans();
        $userId = $this->userDAO->createUser($User);
        if (!$userId) {
            $User->rollback();
            return self::CREATE_USER_FAILED;
        } else {
            $data = $Org->data;
            $data['userId'] = $userId;
            $res = $Org->create($data);
            $orgId = $this->orgDAO->createOrg($Org);
            if (!$res || !$orgId) {
                $User->rollback();
                Log::write(self::LOG_PREFIX . 'createUser(): createOrg failed, $Org:' . $data . '   last sql:' . $Org->getLastSql(), LOG::ERR);
                return self::CREATE_ORG_FAILED;
            }
            $User->commit();
            return array("userId" => $userId, "orgId" => $orgId);
        }

    }

    public function login($params)
    {
        $user = $params['user'];
        $res = $this->userDAO->getUserByTel($user['acctNo']);
        if ($res === false) {
            throw_exception('查询user错误, acctNo:' . $user['acctNo']);
            return sefl::SQL_ERROR;
        }
        if (empty($res) || $res['psd'] !== $user['psd'])
            return self::ACCT_NOT_EXISTS_OR_PSD_NOT_RIGHT;
        $orgList = $this->orgDAO->getOrgIdListByUserId($res['id']);
        if ($orgList === false) {
            throw_exception('查询orgList错误, userId:' . $res['id']);
            return self::SQL_ERROR;
        }
        $res = array();
        $temp = array();
        for ($i = 0; $i < count($orgList); $i++) {
            $temp['userId'] = $orgList[$i];
            $res[$i] = $temp;
        }
        return array("orgId" => $res['id'], "orgList" => $res);
    }


}

?>